package com.knife.tools;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;

import tools.ConvertDocument;
import tools.ConvertVideo;

import com.knife.news.logic.SiteService;
import com.knife.news.logic.impl.SiteServiceImpl;
import com.knife.news.object.Site;
import com.knife.util.CommUtil;
import com.knife.web.Globals;

public class ZipUpload extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private SiteService siteDAO = new SiteServiceImpl();
	private String filext = "";

	@SuppressWarnings("rawtypes")
	public void doPost(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		String ret = "";
		res.setContentType("text/html; charset=UTF-8");
		req.setCharacterEncoding("UTF-8");
		PrintWriter out = res.getWriter();
		// 如果有附件,先上传附件
		// FileItem file = (FileItem) form.get(filefield);
		System.out.println("发现资料，开始执行上传");
		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setSizeThreshold(4096);
		String filename = "";
		String tmpfilePath = Globals.APP_BASE_DIR + "html" + File.separator;
		factory.setRepository(new File(tmpfilePath));
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setSizeMax(5*1024*1024*1024);
		try {
			String sid = CommUtil.null2String(req.getParameter("sid"));
			Site site = new Site();
			if(sid.length()>0){
				site = siteDAO.getSiteById(sid);
			}else{
				site = siteDAO.getSite();
			}
			List fileItems = upload.parseRequest(req);
			Iterator iter = fileItems.iterator();
			while (iter.hasNext()) {
				FileItem item = (FileItem) iter.next();
				if (!item.isFormField()) {
					filename = item.getName();
					filext = FilenameUtils.getExtension(filename);
					if(filext.trim().length()<=0){
						if(filename.lastIndexOf(".")>0){
							filext=filename.substring(filename.lastIndexOf(".")+1,filename.length());
						}
					}
					UUID uid = UUID.randomUUID();
					String newfilename = uid.toString() + "." + filext.toLowerCase();

					System.out.println("文件名为:"+filename+",识别出文件后缀为:" + filext);
					String subdir = "";
					if (filext.equals("jpg") || filext.equals("jpeg")
							|| filext.equals("gif") || filext.equals("bmp")
							|| filext.equals("png")) {
						subdir = "images";
					} else if (filext.equals("doc") || filext.equals("docx")
							|| filext.equals("ppt") || filext.equals("pptx")
							|| filext.equals("xls") || filext.equals("xlsx")
							|| filext.equals("pdf")) {
						subdir = "office";
					} else if (filext.equals("mpg") || filext.equals("wmv")
							|| filext.equals("3gp") || filext.equals("mov")
							|| filext.equals("mp4") || filext.equals("asf")
							|| filext.equals("asx") || filext.equals("flv")) {
						subdir = "videos";
					} else if (filext.equals("mp3") || filext.equals("wma")) {
						subdir = "audios";
					} else {
						subdir = "others";
					}
					String filePath = Globals.APP_BASE_DIR + "html" + File.separator
							+ site.getPub_dir() + File.separator + "upload"
							+ File.separator + subdir + File.separator
							+ Calendar.getInstance().get(Calendar.YEAR)
							+ File.separator
							+ (Calendar.getInstance().get(Calendar.MONTH)+1)
							+ File.separator;
					String pubPath = Globals.APP_BASE_DIR + "wwwroot" + File.separator
							+ site.getPub_dir() + File.separator + "upload"
							+ File.separator + subdir + File.separator
							+ Calendar.getInstance().get(Calendar.YEAR)
							+ File.separator
							+ (Calendar.getInstance().get(Calendar.MONTH)+1)
							+ File.separator;
					long size = item.getSize();
					if ((filename == null || filename.equals("")) && size == 0) {
						continue;
					}
					try {
						File realfile = new File(filePath + newfilename);
						// 保存上传的文件到指定的目录
						if (!(realfile.getParentFile().exists())) {
							realfile.getParentFile().mkdirs();
						}
						if (realfile.exists()) {
							newfilename = newfilename.substring(0,
									newfilename.lastIndexOf("."))
									+ "_1." + filext;
							realfile = new File(filePath + newfilename);
						}
						item.write(realfile);
						// 上传完毕后开始转换
						if (subdir.equals("office")) {
							System.out.println("识别出文档文件，开始转换：" + newfilename);
							ConvertDocument.convertToSWF(
									filePath + newfilename, filePath
											+ newfilename + ".swf");
							newfilename = newfilename + ".swf";
						} else if (subdir.equals("videos")) {
							System.out.println("识别出视频文件，开始转换：" + newfilename);
							if (!filext.equals("flv")) {
								ConvertVideo.convertToFLV(filePath
										+ newfilename, filePath + newfilename
										+ ".flv", filePath + newfilename
										+ ".jpg");
								newfilename = newfilename + ".flv";
							}
						}else if(subdir.equals("audios")){
							System.out.println("识别出音频文件，开始转换：" + newfilename);
							if (!filext.equals("flv")) {
								ConvertVideo.convertAudioToFLV(filePath
										+ newfilename, filePath + newfilename
										+ ".flv");
								newfilename = newfilename + ".flv";
							}
						}
						if(site.getHtml()==1){
							CopyDirectory.copyFile(realfile, new File(pubPath+newfilename));
							if(site.getBig5()==1){
								String big5Path = (filePath + newfilename).replace(site.getPub_dir() + File.separator + "upload", site.getPub_dir() + File.separator + "big5"+File.separator+"upload");
								CopyDirectory.copyFile(realfile, new File(big5Path));
								String big5PubPath = (pubPath+newfilename).replace(site.getPub_dir() + File.separator + "upload", site.getPub_dir() + File.separator + "big5"+File.separator+"upload");
								CopyDirectory.copyFile(realfile, new File(big5PubPath));
							}
						}
						ret = "/html/"+site.getPub_dir()+"/upload/" + subdir + "/"
								+ Calendar.getInstance().get(Calendar.YEAR)
								+ "/"
								+ (Calendar.getInstance().get(Calendar.MONTH)+1)
								+ "/" + newfilename;
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		//System.out.println(ret);
		out.print(ret);
	}
}